package per.turtle.job.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.quartz.CronExpression;
import per.turtle.common.core.annotation.MaxSizeWithCharset;
import per.turtle.common.core.constant.ScheduleConstants;
import per.turtle.common.core.web.entity.BaseEntity;

import javax.validation.constraints.NotBlank;
import java.text.ParseException;
import java.util.Date;

/**
 * 定时任务调度表 sys_job
 *
 * @author turtle
 */
@Data
@EqualsAndHashCode(callSuper = true)
@ToString
public class SysJob extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("任务ID")
    @TableId(type = IdType.AUTO)
    private Long jobId;

    @ApiModelProperty("任务名称")
    @NotBlank(message = "任务名称不能为空")
    @MaxSizeWithCharset(max = 63, message = "任务名称超出限定长度！")
    private String jobName;

    @ApiModelProperty("任务组名")
    private String jobGroup;

    @ApiModelProperty("调用类")
    @NotBlank(message = "调用类不能为空")
    @MaxSizeWithCharset(max = 127, message = "调用类名称超出限定长度！")
    private String invokeClass;

    @ApiModelProperty("调用方法")
    @NotBlank(message = "调用方法不能为空")
    @MaxSizeWithCharset(max = 63, message = "调用方法名称超出限定长度！")
    private String invokeMethod;

    @ApiModelProperty("调用参数")
    @NotBlank(message = "调用参数不能为空")
    @MaxSizeWithCharset(max = 255, message = "调用参数超出限定长度！")
    private String invokeParams;

    @ApiModelProperty("cron执行表达式")
    @NotBlank(message = "Cron执行表达式不能为空")
    @MaxSizeWithCharset(max = 31, message = "Cron执行表达式超出限定长度！")
    private String cronExpression;

    @ApiModelProperty("计划执行错误策略（1：立即执行；2：执行一次；3：放弃执行）")
    private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT;

    @ApiModelProperty("是否并发执行（0：禁止；1：允许）")
    private Boolean concurrent;

    @ApiModelProperty("任务状态（0：正常；1：暂停）")
    private Boolean isDisabled;

    @ApiModelProperty("所属部门id")
    private String deptId;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public Date getNextValidTime() {
        try {
            CronExpression cron = new CronExpression(cronExpression);
            return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

}